import { Button, Card, Form, List, Space, Select, Typography, Input, message, Table } from 'antd';
import React, { useEffect } from 'react';
import { connect, history } from 'umi';
import moment from 'moment';
import AvatarList from '../components/AvatarList';
import ProjectStatus from '../components/ProjectStatus'
import styles from './style.less';
import { STATUS } from '@/consts/project'
import ContentLayout from '@/layouts/ContentLayout'
import ArrayUtils from '@/utils/ArrayUtils'
import Modal from 'antd/lib/modal/Modal';
import { useState } from 'react';
import UserBrief from '@/components/UserBrief';
import ActionDropdown from '@/components/ActionDropdown';
import CheckActon from '../components/CheckActoin'
const { Option } = Select;
const FormItem = Form.Item;
const { Paragraph } = Typography;
const { Search, TextArea } = Input;
import { saveProject } from '@/services/project/project'


const tableColumns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true,
    align: 'center',
    width: 150,
    fixed: 'left',
    sorter: (a, b) => a.name.localeCompare(b.status),
    render: (text, record) => <a className={styles.tableRowName}>{record.name}</a>,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 80,
    key: 'status',
    sorter: (a, b) => a.status - b.status,
    render: (text, record) => <ProjectStatus status={record.status}></ProjectStatus>,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'decription',
    ellipsis: true,
  },
  {
    title: '负责人',
    width: 140,
    dataIndex: 'userId',
    key: 'userId',
    sorter: (a, b) => a.user.nickName && a.user.nickName.localeCompare(b.user.nickName),
    render: (text, record) => <UserBrief user={record.user} showUsername={false}></UserBrief>,
  },
  {
    title: '成员数量',
    width: 100,
    dataIndex: 'memberCnt',
    key: 'memberCnt',
    sorter: (a, b) => a.memberCnt - b.memberCnt,
    render: (text, record) => <a>{record.memberCnt}</a>,
  },
  {
    title: '产生工时',
    width: 100,
    dataIndex: 'memberCnt',
    key: 'memberCnt',
    sorter: (a, b) => a.memberCnt - b.memberCnt,
    render: (text, record) => <a>{record.memberCnt}</a>,
  },
  {
    title: '进行中任务',
    width: 110,
    dataIndex: 'doingTaskCnk',
    key: 'doingTaskCnk',
    sorter: (a, b) => a.doingTaskCnk - b.doingTaskCnk,
    render: (text, record) => <a>{record.doingTaskCnk}</a>,
  },
]



const getKey = (id, index) => `${id}-${index}`;

const Projects = (props) => {
  const {
    dispatch,
    projectData: { list = [] },
    loading,
    queryInitParams
  } = props
  const [form] = Form.useForm();
  const [showType, setShowType] = useState("table")
  const [createProjectModalVisibal, setCreateProjectModalVisibal] = useState();
  const [showList, setShowList] = useState([])
  const [params, setParams] = useState({
    pageNum: 1,
    pageSize: 10
  })

  useEffect(() => {
    console.log(queryInitParams)
    queryProjectPage(queryInitParams)
  }, []);

  useEffect(() => {
    setShowList(list)
  }, [list])

  const nagtiveToProjectDetail = (project) => {
    console.log(project)
    history.push(`/projects/${project.id}/detail`)
  }

  const table = showList && (
    <Table columns={tableColumns}
      pagination={false}
      rowKey="id"
      size="small"
      dataSource={showList}
      onRow={record => {
        return {
          onClick: () => { nagtiveToProjectDetail(record) }
        }
      }}
      scroll={{ x: 1000 }}
    >
    </Table>
  )

  const cardList = showList && (
    <List
      rowKey="id"
      loading={loading}
      grid={{
        gutter: 16,
        xs: 3,
        sm: 3,
        md: 3,
        lg: 3,
        xl: 4,
        xxl: 4,
      }}
      className={styles.coverCardList}
      dataSource={showList}
      renderItem={(item) => (
        <List.Item>
          <Card
            className={styles.card}
            hoverable
            onClick={() => nagtiveToProjectDetail(item)}
          >
            <Card.Meta
              title={<>
                <a>{item.name}</a>
                <div className={styles.projectCardStatus}><ProjectStatus status={item.status}></ProjectStatus></div>
              </>}
              description={
                <Paragraph
                  className={styles.description}
                  ellipsis={{
                    rows: 3,
                  }}
                >
                  {item.description}
                </Paragraph>
              }
            />

            <Space align="center" wrap className={styles.cardItemContent}>
              <span>成员数：<a>{item.memberCnt}</a> </span>
              <span>产生工时：<a>{item.doingTaskCnk}</a> </span>
              <span>进行中任务：<a>{item.doingTaskCnk}</a> </span>
            </Space>
            <Space align="center" className={styles.cardItemContent}>
              <span>{moment(item.createTime).fromNow()}</span>
              <div className={styles.avatarList}>
                <AvatarList>
                  <AvatarList.Item
                    key='more'
                    tips='更多'
                  />
                  <AvatarList.Item
                    key={item.user.id}
                    src={item.user.avatarUrl}
                    tips={item.user.nickName}
                  />
                </AvatarList>
              </div>
            </Space>
          </Card>
        </List.Item>
      )}
    />
  );


  const onParamChange = (param,doQuery) => {
    if (param && !param.pageNum) {
      param.pageNum = 1;
    }
    let newParams = { ...params, ...param }
    setParams(newParams)
    dispatch({
      type: 'queryParams/saveQueryParams',
      payload: {
        name: "projectPage",
        params: newParams
      }
    });
    if (doQuery) {
      queryProjectPage(newParams)
    }
  }

  const queryProjectPage = (queryParams) => {
    dispatch({
      type: 'project/page',
      payload: queryParams || params
    });
  }

  const saveNewProject = async () => {
    const value = await form.validateFields()
    console.log(value)
    saveProject(value).then(({ success }) => {
      if (success) {
        message.success("保存成功！")
        setCreateProjectModalVisibal(false)
        onParamChange()
      }
    })
  }

  const actionHeader = [
    <ActionDropdown
      key="actions"
      placement="bottomRight"
      actions={[
        <CheckActon
          check={params?.isArchived === 1}
          onChange={(value) => {
            if (value) {
              onParamChange({
                isArchived: 1
              }, true)
            } else {
              onParamChange({
                isArchived: null
              }, true)
            }
          }}
          label={'查看归档数据'}
        />,
      ]}
    />,
    <Button type="primary" size="middle" onClick={() => {
      setCreateProjectModalVisibal(true)
    }}>
      新增项目
  </Button>,
    <>布局：
      <Select defaultValue={"table"} onChange={(value) => setShowType(value)} size="middle">
        <Select.Option value={"table"}>
          表格
    </Select.Option>
        <Select.Option value={"card"}>
          卡片
    </Select.Option>
      </Select></>,
    <Search placeholder="项目名" onSearch={(name) => {
      if (!name || name.trim() === "") {
        setShowList(list)
      } else {
        setShowList(list.filter(item => item.name.indexOf(name) > -1))
      }
    }} size="middle" />,
  ]


  const queryItems = [
    {
      name: "mySelection",
      label: "选项",
      isMain: true,
      type: "radio",
      options: [
        { value: null, label: "全部" },
        { value: 1, label: "我负责的" },
        { value: 2, label: "我参与的" }]
    }
    ,
    {
      name: "inStatus",
      label: "状态",
      type: "tagSelect",
      span: 12,
      options: ArrayUtils.jsonToArray(STATUS).filter(item => item.value.isSelect !== 0).map(item => {
        return { value: item.key, label: item.value.name }
      })
    },
    {
      name: "inUserId",
      label: "负责人",
      type: "userSelect",
      span: 12,
    }
  ]

  return (
    <>
      <ContentLayout
        content={showType === "table" ? table : cardList}
        onQueryChange={onParamChange}
        queryInitParams={queryInitParams}
        queryItems={queryItems}
        actionHeader={actionHeader}
      >
      </ContentLayout>
      <Modal
        visible={createProjectModalVisibal}
        closable
        title={"创建项目"}
        onCancel={() => {
          setCreateProjectModalVisibal(false);
        }}
        onOk={() => {
          saveNewProject()
        }}
        destroyOnClose
        okText={"确认"}
        cancelText={"取消"}
      >
        <Form
          form={form}
        >
          <FormItem
            label={"标题"}
            name="name"
            rules={[
              {
                required: true,
                message: "请填入标题",
              },
            ]}
          >
            <Input maxLength={20}></Input>
          </FormItem>
          <FormItem label={"描述"}
            name="description"
            rules={[
              {
                required: true,
                message: "请填入描述",
              },
            ]}
          >
            <TextArea maxLength={200} showCount rows={4}></TextArea>
          </FormItem>
        </Form>
      </Modal>
    </>
  )
};

export default connect(({ project, loading, queryParams }) => ({
  projectData: project.projectData,
  queryInitParams: queryParams.projectPage,
  loading: loading.models.project,
}))(Projects);
